<?php
/**
 * Created by sublime 3.
 * Auth: Inhere
 * Date: 14-6-22
 * Time: 10:35
 * Uesd: 主要功能是 用户验证
 */
namespace ulue\parts;

use Ulue;
use ulue\core\abstracts\AbstractCore;
use ulue\parts\security\Token;

class User extends AbstractCore
{

    protected $_key            = 'lkjdfdouerdsdfxcg';
    // private $_isLoginKey     = 'isLogin';

    /**
     * expires (minutes)
     */
    public $expires = '20';

    public $loginUrl = '/site/login';

    public $logoutShowUrl = '/';

    /**
     * 来源地址
     * @var null|string
     */
    protected $fromUrl = null;

    protected $isTimeout = false;

    public function __construct(array $options=[])
    {
        if ($options) {
            $this->bind($options);
        }
    }

    public function bind(array $options)
    {
        foreach ($options as $attr => $value) {
            if (property_exists($this, $attr)) {
                $this->$attr = $value;
            }
        }

        return $this;
    }

    public function setFromUrl($value)
    {
        $this->fromUrl = $_SESSION['fromUrl'] =  trim($value);

        return $this;
    }

    public function getFromUrl()
    {
        if ( !$this->fromUrl ) {

            $homeUrl = \Ioc::get('app.uri')->get('home.url');
            $this->fromUrl = \Ioc::getRequest()->getSession('fromUrl', $homeUrl);

            // $url = !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : $homeUrl;

            // if (strstr($url, $_SERVER['REQUEST_URI'])) {
            //     $this->fromUrl = $homeUrl;
            // } else {
            //     $this->fromUrl = $url;
            // }
        }

        return $this->fromUrl;
    }

    /**
     * 退出登录后显示的页面地址, 默认跳到首页
     */
    public function getLogoutShowUrl()
    {
        if ( !$this->logoutShowUrl ) {
            return $this->loginUrl;
        }

        return $this->logoutShowUrl;
    }

    public function getSecureKey()
    {
        return Token::md5($this->_key);
    }

    public function setKey($value)
    {
        $this->_key = (string)$value;

        return $this;
    }

    public function getKey()
    {
        return $this->_key;
    }

    #
    public function login(array $data)
    {
        $_key    = $this->getSecureKey();

        $info = [
            $_key                => serialize($data),
            'start.active.time' => time(),
            'isLogin'           => '1',
            // 'token'             => crypt($data['id']),
        ];

        foreach ($info as $key => $value) {
            $this->set($key,$value);
        }

        $this->fromUrl = \Ioc::get('app.request')->getParam('fromUrl');

        return true;
    }

    public function verfiy()
    {

    }

    public function getAll()
    {
        $data = \Ioc::getSession()->get( $this->getSecureKey() );

        return unserialize($data);
    }

    public function get($name)
    {
        $name = trim($name);
        $data = $this->getAll();

        return array_key_exists($name, $data) ? $data[$name] : false;
    }

    public function set($name, $value )
    {
        if( $name ) {
            \Ioc::getSession()->set( $name , $value );
        }

        return $this;
    }

    public function logout()
    {
        if ( \Ioc::getSession()->destroy() ) {
            return true;
        }

        throw new \DRuntimeException("has Error!!" );
    }

    /**
     * updateActiveTime 检查登录时间是否超时]
     * @return [type] [description]
     */
    private function _checkLoginTimeout()
    {
        // 没超时 更新活动时间起点...
        if ( !$this->getIsTimeout() ) {

            \Ioc::getSession()->set('start.active.time', time());

            return true;
        }

        $this->setIsTimeout();

        return false;
    }

    /**
     * 是否登陆超时 超时 true 未超时 false
     * @return bool
     */
    public function getIsTimeout()
    {
        if ($this->isTimeout === true) {
            return true;
        }

        $lastActiveTime = \Ioc::getSession()->get('start.active.time');

        // 未登录
        if (!$lastActiveTime || !is_integer($lastActiveTime)) {
            return false;
        }

        $timeDifference = time()-$lastActiveTime;

        return $timeDifference > ($this->expires * 60);
    }

    public function setIsTimeout($value=true)
    {
        $this->isTimeout = (bool)$value;

        return $this;
    }

    public function reLogin()
    {
        $url = $this->loginUrl . '?fromUrl=' . \Ioc::get('app.uri')->get('current.path');

        \Ioc::get('app.uri')->doneJump($url, [
                    'msg'       => 'Login timeout, please login again!',
                    'time'      => '3',
                    'btnText'   => 'Login Page',
                ]);

        // Ulue::$app->quit($string);
    }

    public function getIsLogin()
    {
        if ('1' === \Ioc::getSession()['isLogin'] ) {

            return $this->_checkLoginTimeout();
        }

        return false;
    }

    public function __get($name)
    {
        $method = 'get'.ucfirst( $name );

        if (method_exists($this, $method)) {

            return $this->$method();
        }

        if ( ($value = $this->get($name)) !== false ) {

            return $value;
        }

        if (method_exists($this, 'set'.ucfirst( $name ))) {
            throw new \DRuntimeException("Getting a Write-only property! ".get_class($this)."::{$name}", 'get');
        }

        throw new \DRuntimeException("Getting a Unknown property! ".get_class($this)."::{$name}", 'get');
    }
}
